package com.slg.android.manyanime;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.slg.android.manyanime.adapter.CommonPageAdapter;

import com.slg.android.manyanime.bean.Hua;
import com.slg.android.manyanime.utils.ApiUtils;
import com.slg.android.manyanime.utils.DataStore;
import com.slg.android.manyanime.utils.HttpTool;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;


public class ReadCartoonActivity extends FragmentActivity implements GestureDetector.OnGestureListener
        , View.OnClickListener, ViewPager.OnPageChangeListener {


    // bh_probar = new ProgressBar(context,null,android.R.attr.progressBarStyleHorizontal);
    private static final int FLING_MIN_DISTANCE = 120;//移动最小距离
    private static final int FLING_MIN_VELOCITY = 200;//移动最大速度

    private ProgressDialog progressBar;

    @ViewInject(R.id.read_cartoon_bottom_layout)
    private LinearLayout bottomlayout;

    @ViewInject(R.id.read_cartoon_top_layout)
    private RelativeLayout toplayout;

    @ViewInject(R.id.read_cartoon_viewPage)
    private ViewPager viewPager;

    @ViewInject(R.id.common_loading)
    private RelativeLayout loading;

    @ViewInject(R.id.common_loading_image)
    private ImageView loadingImg;

    @ViewInject(R.id.read_cartoon_title_back)
    private ImageView titleBack;

    @ViewInject(R.id.read_cartoon_collect)
    private ImageView collect;


    List<String> pagePath;


    private Handler mhandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            int what = msg.what;
            switch (what) {
                case 1:
                    if (toplayout.getVisibility() != View.VISIBLE) {
                        toplayout.setVisibility(View.VISIBLE);
                    }
                    if (bottomlayout.getVisibility() != View.VISIBLE) {
                        bottomlayout.setVisibility(View.VISIBLE);
                    }

                    break;
                case 2:
                    if (toplayout.getVisibility() != View.GONE) {
                        toplayout.setVisibility(View.GONE);
                    }
                    if (bottomlayout.getVisibility() != View.GONE) {
                        bottomlayout.setVisibility(View.GONE);
                    }
            }
        }
    };

    private ArrayList<String> ids;
    ;
    private int hua;

    private HttpUtils httpUtils;

    private CommonPageAdapter pageAdapter;

    private String cartName;

    BitmapUtils bitmapUtils;

    ArrayList<String> pageUrls;

    String huaName;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_read_cartoon);
        ViewUtils.inject(this);
        httpUtils = new HttpUtils();
        titleBack.setOnClickListener(this);
        bitmapUtils = DataStore.getBitmapUtils();
        Intent intent = getIntent();
        huaName = intent.getStringExtra("huaName");
        hua = intent.getIntExtra("hua", 0);
        //Log.i("str","hua="+hua);
        int type = intent.getIntExtra("type", 0);//类型
        cartName = intent.getStringExtra("cartName");

        ids = intent.getStringArrayListExtra("hualist");
        Log.i("str", ids.toString());
        pageUrls = new ArrayList<>();
        getPageUrl(ids.get(hua - 1), true);
        Log.i("str", pageUrls.toString());


        viewPager.setOnPageChangeListener(this);
        Log.i("str", "pageUrls onCreate" + pageUrls.size());
//        if (!TextUtils.isEmpty(cartName) && hua != 0) {
//            cartooninfo.setText(cartName + "  第" + currentHua + "话 " + currenPage + "/" + pageUrls.size());
//            cartooninfobottom.setText(cartName + "  第" + currentHua + "话 " + currenPage + "/" + pageUrls.size());
//        }

        Log.i("str", "pageUrls onCreate innner" + pageUrls.size());
        titleBack.setOnClickListener(this);


    }

    //构造收拾探测器
    GestureDetector mygesture = new GestureDetector(this);


    @Override
    public boolean onDown(MotionEvent e) {
        return false;
    }

    @Override
    public void onShowPress(MotionEvent e) {
        Message message = mhandler.obtainMessage();
        message.what = 1;
        mhandler.sendMessage(message);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(3000);
                } catch (Exception e) {
                    e.printStackTrace();

                }
            }
        });
        message = mhandler.obtainMessage();
        message.what = 2;
        mhandler.sendMessage(message);

    }

    @Override
    public boolean onSingleTapUp(MotionEvent e) {
        return false;
    }

    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
        return false;
    }

    /* 用户长按触摸屏，由多个MotionEvent ACTION_DOWN触发*/
    @Override
    public void onLongPress(MotionEvent e) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Message message = mhandler.obtainMessage();
                    message.what = 1;
                    mhandler.sendMessage(message);
                    Thread.sleep(3000);
                    message = mhandler.obtainMessage();
                    message.what = 2;
                    mhandler.sendMessage(message);

                } catch (Exception e) {
                    e.printStackTrace();

                }
            }
        }).start();


    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        if (e1.getX() - e2.getX() > FLING_MIN_DISTANCE
                && Math.abs(velocityX) > FLING_MIN_VELOCITY) {
            Toast.makeText(this, "向左移", Toast.LENGTH_LONG).show();
            loadLeftImage();
        }
        //向左翻图片
        if (e2.getX() - e1.getX() > FLING_MIN_DISTANCE
                && Math.abs(velocityX) > FLING_MIN_VELOCITY) {
            Toast.makeText(this, "向右移", Toast.LENGTH_LONG).show();
            loadRightImage();
        }
        return false;

    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return mygesture.onTouchEvent(event);
    }


    public void loadLeftImage() {

    }

    public void loadRightImage() {

    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.read_cartoon_title_back:
                finish();
                break;
        }

    }

    int currentPostion;//滑动位置
    int currentPageScrollStatus;//滑动状态

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        if (position == 0) {
            if (positionOffsetPixels == 0 && currentPageScrollStatus == 1) {
                Toast.makeText(ReadCartoonActivity.this, "已经到最前面了", Toast.LENGTH_LONG).show();
                if (hua != 1) {
                    //getPageUrl(ids.get(currentHua - 1 - 1), false);
                }

            }
        }
        if (position == pageUrls.size() - 1) {
            if (positionOffsetPixels == 0 && currentPageScrollStatus == 1) {
                Toast.makeText(ReadCartoonActivity.this, "已经到最后面了", Toast.LENGTH_LONG).show();
                //getPageUrl(ids.get(currentHua), true);
            }
        }
    }

    @Override
    public void onPageSelected(int position) {

        currentPostion = position;
    }

    @Override
    public void onPageScrollStateChanged(int state) {
        //记录page滑动状态，如果滑动了state就是1
        currentPageScrollStatus = state;

    }

    public void getPageUrl(String id, final boolean isEnd) {

        httpUtils = new HttpUtils();
        httpUtils.send(HttpRequest.HttpMethod.GET
                , ApiUtils.CARTOON_PAGES + id,
                new RequestCallBack<String>() {
                    @Override
                    public void onSuccess(ResponseInfo<String> stringResponseInfo) {
                        String result = stringResponseInfo.result;
                        Log.i("str", result);
                        ArrayList innerList = new ArrayList();
                        try {
                            JSONArray array = new JSONArray(result);
                            for (int i = 0; i < array.length(); i++) {
                                Log.i("str", array.getString(i));
                                //Log.i("str", "pageUrls" + pageUrls.size());
//                                if (!pageUrls.contains(array.getString(i))&&isEnd){
//                                    pageUrls.add(array.getString(i));
//                                }else if(!pageUrls.contains(array.getString(i))&&isEnd){
//
//                                }
                                innerList.add(array.getString(i));
                            }
                            if (isEnd) {
                                if (!pageUrls.contains(innerList)) {
                                    pageUrls.addAll(innerList);

                                }

                            } else {
                                if (!pageUrls.contains(innerList)) {
                                    pageUrls.addAll(0, innerList);

                                }
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        } finally {

                            CommonPageAdapter adapter = new CommonPageAdapter(ReadCartoonActivity.this, pageUrls, cartName,
                                    huaName);
                            viewPager.setAdapter(adapter);
//
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, String s) {
                        Toast.makeText(ReadCartoonActivity.this, R.string.no_network, Toast.LENGTH_LONG).show();
                    }
                });

    }
}

